// pages/order/index.js
import {request} from '../../request/index.js'
import regeneratorRuntime from '../../lib/runtime/runtime.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        id: 0,
        name: "全部",
        isActive: true
      },
      {
        id: 1,
        name: "待付款",
        isActive: false
      },
      {
        id: 2,
        name: "待发货",
        isActive: false
      },
      {
        id: 3,
        name: "退货/退款",
        isActive: false
      }
    ],
    orders: []
  },
  tabsItemChange: function (e) {
    let index = e.detail.index
    let tabs = this.data.tabs
    this.handleItemIndexChange(index + 1)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    // 判断如果没有token跳转到授权页面
    const token = wx.getStorageSync("token");
    // if (!token) {
    //   wx.navigateTo({
    //     url: '/pages/auth/index',
    //   })
    //   return 
    // }
      
    // 1. 获取当前的页面栈
    let page =  getCurrentPages();
    // 2. 获取当前页面
    let currentPage = page[page.length - 1]
    // 3. 获取当前页面里传过来的参数
    let type = currentPage.options.type
    // 4.根据这个参数请求数据  
    this.getOrders(type)
    this.handleItemIndexChange(type)
    
  },
  handleItemIndexChange: function (type) {
    var tabs = this.data.tabs
    tabs.forEach(v => {
      if(v.id == type - 1) {
        v.isActive = true
      } else {
        v.isActive = false 
      }
    })
    this.setData({
      tabs
    })
  },
  // 获取订单列表方法
  async getOrders(type) {
    const res = await request({
      url: '/my/orders/all',
      data: {type}
    })
    this.setData({
      orders: res.orders
    })
  }

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
})